package jwt

import (
	"github.com/gin-gonic/gin"
	"net"
)

// SetRefreshToken 设置Refresh Token的cookie，MAxAge就是在浏览器中缓存能存在的时间
func SetRefreshToken(c *gin.Context, token string, maxAge int) {
	// 获取请求的host，如果失败则取原始请求host
	host, _, err := net.SplitHostPort(c.Request.Host)
	if err != nil {
		host = c.Request.Host
	}
	// 调用setCookie设置refresh-token
	setCookie(c, "x-refresh-token", token, maxAge, host)
}

// ClearRefreshToken 清除Refresh Token的cookie
func ClearRefreshToken(c *gin.Context) {
	// 获取请求的host，如果失败则取原始请求host
	host, _, err := net.SplitHostPort(c.Request.Host)
	if err != nil {
		host = c.Request.Host
	}
	// 调用setCookie设置cookie值为空并过期，删除refresh-token
	setCookie(c, "x-refresh-token", "", -1, host)
}

// setCookie 设置指定名称和值的cookie
func setCookie(c *gin.Context, name, value string, maxAge int, host string) {
	// 判断host是否是IP地址
	if net.ParseIP(host) != nil {
		// 如果是IP地址，设置cookie的domain为“/”
		c.SetCookie(name, value, maxAge, "/", "", false, true)
	} else {
		// 如果是域名，设置cookie的domain为域名
		c.SetCookie(name, value, maxAge, "/", host, false, true)
	}
}

// GetAccessToken 从请求头获取Access Token
func GetAccessToken(c *gin.Context) string {
	// 获取x-access-token头部值
	token := c.Request.Header.Get("x-access-token")
	return token
}

// GetRefreshToken 从cookie获取Refresh Token
func GetRefreshToken(c *gin.Context) string {
	// 尝试从cookie中获取refresh-token
	token, _ := c.Cookie("x-refresh-token")
	return token
}
